package com.example.seckill.Controller;

import com.example.seckill.Exception.ErrorEnum;
import com.example.seckill.Exception.GlobalException;
import com.example.seckill.Util.JwtTokenUtil;
import com.example.seckill.Util.MD5Util;
import com.example.seckill.VO.LoginRequest;
import com.example.seckill.VO.UserVO;
import com.example.seckill.annotation.CurrentUser;
import com.example.seckill.common.CommonResult;
import com.example.seckill.VO.TokenResponse;
import com.example.seckill.mapper.PermissionMapper;
import com.example.seckill.mapper.RoleMapper;
import com.example.seckill.mapper.UserMapper;

import com.example.seckill.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.management.relation.Relation;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class AuthController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    RoleMapper roleMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private PermissionMapper permissionMapper;

    /**
     * 描述： 测试用
     *
     * @param
     * @return
     */

    @GetMapping("/info")
    public CommonResult info(@CurrentUser User user){
        UserVO userVO= new UserVO();
        userVO.setUsername(user.getUsername());
        userVO.setGender(user.getGender());
        userVO.setName(user.getName());

        // 1. 从user_role表通过用户id查询所有的角色信息
        Integer userId = Math.toIntExact(user.getId());
        List<UserRole> userRoles = roleMapper.getUserRoleByUserId(userId);
//        System.out.println(1);
        // 设置角色id
        HashSet<Permission> permissionSet = new HashSet<>();
        userVO.setRoles(userRoles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList()));
//        System.out.println(2);
        for (UserRole userRole : userRoles) {
            // 2.根据roleId从role_permission表查询出所有的permissionId
            List<RolePermission> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermission rolePermission : rolePermissions) {
                Integer permissionId = rolePermission.getPermissionId();
                // 3. 根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }
        System.out.println(3);
        // 对资源根据id进行排序
        LinkedHashSet<Permission> sortedSet = permissionSet.stream().filter(u->u!=null).sorted(Comparator.comparing(Permission::getId)).collect(Collectors.toCollection(LinkedHashSet::new));
        //设置当前用户的资源信息
        System.out.println(4);
        userVO.setPermissions(sortedSet);
        return CommonResult.success(userVO);
    }



    @PostMapping("/login")
    public CommonResult<?> login(@RequestBody LoginRequest loginUser) {


        String username=loginUser.getUsername();
        String key = "LoginUserInfo:" + username;
        User u;

        //从Redis中取用户信息,如果Redis中存在则从Redis拿数据,否则从数据库取数据

        User user=(User)redisTemplate.opsForValue().get(key);
        //System.out.println("密码一样："+loginUser.getPassword().equals(user.getPassword()));
        //如果redis中没有数据
        if(user==null){
        user = userMapper.findByUsername(loginUser.getUsername());
//            System.out.println("数据库取数据");
        }
        if (user == null) {
            System.out.println("用户不存在");
            throw new GlobalException(ErrorEnum.LOGIN_ERROR);
        }


        String salt=user.getSalt();
        String dbpassword= MD5Util.formPassToDBPass(loginUser.getPassword(),salt);
       

         if (!dbpassword.equals(user.getPassword())) {
            throw new GlobalException(ErrorEnum.LOGIN_ERROR);
        }

        //存入redis当中
        else redisTemplate.opsForValue().set(key,user);

        //生成Token
        String accessToken = jwtTokenUtil.generateAccessToken(username);
        String refreshToken = jwtTokenUtil.generateRefreshToken(username);
        TokenResponse token_resp = new TokenResponse(accessToken, refreshToken);
        return CommonResult.success(token_resp);
    }
}
